<?php

/**
 * vente-unique Product Collection Class
 *
 * @package    
 * @subpackage doctrine_collection
 * @author     Guillaume
 */
class vuProductCollection extends Doctrine_Collection {
  
  public function getInfosFromBack()  {
    return $this->getInfos('catalog', true);
  }
  /*
  Méthode qui contruit un tableau avec toutes les infos nécessaires a l'affichage d'une
  collection de produits
  */
  public function getInfos($type = 'catalog', $fromBack = false) {
		
    sfProjectConfiguration::getActive()->loadHelpers(array("I18N"));
    
    $infos = array();
    $keys  = array();
    $keysGrouped = array();

    $arraySkuIds = array();
    $arrayProductIds = array();
    $arrayLinkPrice = array();
    $arrayChildWithQuantity = array();
    $arrayProductsGrouped = array();
    $storeId = 0;
    
    // debug memcache result
    if(is_array($this->data) && array_key_exists(0,$this->data) && $this->data[0] == null){
      $dispatcher = sfProjectConfiguration::getActive()->getEventDispatcher();
      $dispatcher->notify(new sfEvent($this, 'application.log', array('message' => 'add product error - Check key memcache','priority'=>sfLogger::ERR)));
      return $infos;
    }
    
    $i = 1;
    foreach ($this->data as $product) {
      if(!is_object($product)){
            //log
        $dispatcher = sfProjectConfiguration::getActive()->getEventDispatcher();
        $dispatcher->notify(new sfEvent($this, 'application.log', array('message' => 'vuProductCollection Object Product is null','priority'=>sfLogger::ERR)));
        continue;
      }

      if($storeId == 0) $storeId = $product->store_id;
      // on ne prend pas en compte les produits de type service
      if($product->type != Product::_SERVICE) {
        // construnction d'un tableur de sku_id
        $productSkuIds = $product->getSkuIds();
        $arraySkuIds = array_merge($arraySkuIds, $productSkuIds);
        
        if($product->getIsParametrable() && ($type == 'catalog' || $type == 'product')) {
          $arrayProductIds[] = $product->getDefaultChildren()->id;
          if(!array_key_exists($product->getDefaultChildren()->id,$arrayLinkPrice)){
            $arrayLinkPrice[$product->getDefaultChildren()->id] = array();    
          }
          $arrayLinkPrice[$product->getDefaultChildren()->id][] = $product->id;         
        }
        else {
          $arrayProductIds[] = $product->id;
          if(!array_key_exists($product->id,$arrayLinkPrice)){
            $arrayLinkPrice[$product->id] = array();    
          }
          $arrayLinkPrice[$product->id][] = $product->id;
        }
        
        $infos = $this->copyInfos($infos,$product,$type);
        
        if($product->getIsParametrable()){
          $infos[$product->id]['deliveryMode']     = $product->getDefaultChildren()->transport_type;
          $infos[$product->id]['deliveryBox']      = $product->getDefaultChildren()->RetrieveDeliveryBox();
        }
        
        $i++;
      }
    }
    
    if($storeId == 0) $storeId = 1;
    $arrayWarehousesIds = Warehouse::getAvailableWarehouses($storeId);
    
    $arrayStocks = Doctrine::getTable('Stock')->findMultiAllStocksByWarehouses($arrayWarehousesIds,$arraySkuIds,$fromBack);

    
    foreach ($this->data as $product) {
      // on ne prend pas en compte les produits de type service
      if($product->type != Product::_SERVICE) {
        $infos[$product->id]['ConsolidatedStocks'] = $product->getConsolidatedStock( $arrayStocks , $fromBack );
        $infos[$product->id]['isSellable'] = false;
        if( is_array($infos[$product->id]['ConsolidatedStocks']) 
         && !empty($infos[$product->id]['ConsolidatedStocks'])
         && $product->isViewInFront()
        ){
          $infos[$product->id]['isSellable'] = true;
        }
        if(!empty($infos[$product->id]['ConsolidatedStocks'])) {
          
          // trier dans la requete sql
          $defaultStock = $infos[$product->id]['ConsolidatedStocks'][0];
          

          if($defaultStock['type'] == Stock::_ENSTOCK) {
            $infos[$product->id]['disponibility'] = 'EN STOCK'; 
          }
          /*elseif($defaultStock['type'] == Stock::_HORSSTOCK) {
            $infos[$product->id]['disponibility'] = ':) HORS STOCK'; 
          }*/

          $infos[$product->id]['RemoveToDeposit'] = $product->getRemoveToDeposit($arrayStocks);

        }
      }
    }

    // prices 
    if($arrayProductIds){
      $infos = $this->copyPrices($storeId,$infos,$arrayProductIds,$arrayLinkPrice);
    }

    // Pour les produits qui n'ont pas de prix valide on créé un prix par rapport à  pricewhennovalid
    /*foreach ($this->data as $product) {
      if (!isset($infos[$product->id]['Price'])){ 
        $infos[$product->id]['Price']['ttc']              = $product->pricewhennovalid;
        $infos[$product->id]['Price']['ht']               = Store::getPriceHT($product->store_id, $product->pricewhennovalid );
        $infos[$product->id]['Price']['ref']              = $product->pricewhennovalid;
        $infos[$product->id]['Price']['label']            = '';
        $infos[$product->id]['Price']['template']         = $product->store_id == Store::_ALLEMAGNE ? 'traditionnelle_allemagne' : 'traditionnelle';
        $infos[$product->id]['Price']['tagFirst']         = 0;
        $infos[$product->id]['Price']['tagSecond']        = 0;
        $infos[$product->id]['Price']['hasPriceRef']      = false;
        $infos[$product->id]['Price']['description']      = '';
        $infos[$product->id]['Price']['publish_end_at']   = '';
        $infos[$product->id]['Price']['publish_start_at'] = '';
      }
    }*/
    
     return $infos;
  }
  
  
  private function copyInfos($infos, $object, $type) {
    $infos[$object->id]['id']               = $object->id;
    $infos[$object->id]['sku_id']           = $object->sku_id;
    $infos[$object->id]['title']            = $object->title;
    $infos[$object->id]['slug']             = $object->slug;
    $infos[$object->id]['imagePath']        = $object->image_path_for_transform;
    $infos[$object->id]['brand_id']         = $object->brand_id != '' ? $object->brand_id : 0 ;
    $infos[$object->id]['promo_id']         = 0;
    $infos[$object->id]['deliveryMode']     = $object->transport_type;
    $infos[$object->id]['deliveryBox']      = $object->RetrieveDeliveryBox();
    $infos[$object->id]['status_id']        = $object->status_id;
    $infos[$object->id]['publish_start_at'] = $object->publish_start_at;
    $infos[$object->id]['publish_end_at']   = $object->publish_end_at; 
    $infos[$object->id]['only_quantity']    = $object->only_quantity; 
    $infos[$object->id]['isContermarque']   = $object->is_contremarque;
    $infos[$object->id]['isSellable']       = false;
    $infos[$object->id]['disponibility']    = '';   
    $infos[$object->id]['disponibilityStyle'] = "disponibilityOrange";
    $infos[$object->id]['type']             = $object->type;
    $infos[$object->id]['typeTranslated']   = $object->typeTranslated;
    $infos[$object->id]['isFlash']          = 0;    
    $infos[$object->id]['isPromo']          = false;    
    $infos[$object->id]['isFutureFlash']    = 0;    
    $infos[$object->id]['skuIds']           = $object->getSkuIds();
    $infos[$object->id]['productTypeId']    = $object->getProductTypeId();

    if($infos[$object->id]['deliveryMode'] == '') {
      $infos[$object->id]['deliveryMode'] = 1;
    }
    if($type == 'product') {
      $infos[$object->id]['priceDeliveryZone1'] = $object->delivery_sgl_zone1;
      $infos[$object->id]['priceDeliveryZone2'] = $object->delivery_sgl_zone2;
    }
    
    if($object->type == Product::_GROUPED) {
    	foreach($object->Bundle as $bundle) {
    		 $infos[$object->id]['Bundle'][$bundle->Product->id] = $bundle->quantity;
    	}
    }
    
    return $infos;
  }
  
  private function copyPrices($storeId,$infos,$list,$arrayLinkPrice) {
		
    $productsWithPrices = Doctrine_Core::getTable('Product')->findProductsWithPrice($storeId,$list);

    foreach ($productsWithPrices as $product) {
      // sur une meme page : un parametrable et un enfant sold_as_unique
      $product_price = $product->price;
      // skip no price
      if(!$product_price){
        continue;
      }
      foreach($arrayLinkPrice[$product->id] as $productId){
        $infos[$productId]['Price']['ttc']              = $product_price->price;
        $infos[$productId]['Price']['ht']               = $product_price->price_ht;
        $infos[$productId]['Price']['ref']              = $product->reference_price;
        $infos[$productId]['Price']['label']            = $product_price->price_label;
        $infos[$productId]['Price']['template']         = $product_price->tag_template;
        $infos[$productId]['Price']['tagFirst']         = $product_price->tag_first_demarque;
        $infos[$productId]['Price']['tagSecond']        = $product_price->tag_second_demarque;
        $infos[$productId]['Price']['hasPriceRef']      = $product->hasPriceRef();
        $infos[$productId]['Price']['description']      = $product_price->description;
        $infos[$productId]['Price']['publish_end_at']   = $product_price->publish_end_at;
        $infos[$productId]['Price']['publish_start_at'] = $product_price->publish_start_at;
        if($product->price->isFlashSellPrice() == 1) {
          $infos[$productId]['isFlash']             = 1;  
          $infos[$productId]['disponibility']       = 'VENTE FLASH !';  
          $infos[$productId]['disponibilityStyle']  = "disponibilityRed"; 
        }
        if($product->price->isFutureFlashSellPrice() == 1) {
          $infos[$productId]['isFutureFlash'] = 1;  
        }
        if($product->price->isPromo() == 1) {
          $infos[$productId]['isPromo'] = true;  
        }
        
      }
    }
    return $infos;
  }

  public static function getStock($infos,$stockId) {
    foreach($infos['ConsolidatedStocks'] as $stock) {
      if($stock['id'] == $stockId){
        return $stock;
      }
    }
    return null;
  }
  
  public static function getRemoveToDeposit($infos,$stockId,$is_grouped = false) {

    if(!$infos['RemoveToDeposit']){
      return null;
    }

    if($is_grouped && count($infos['RemoveToDeposit']) > 0){
      return $infos['RemoveToDeposit'][0];
    }
    
    foreach($infos['RemoveToDeposit'] as $stock) {
      if($stock['stock_id'] == $stockId){
        return $stock;
      }
    }
    return null;
  }
  
}


